package com.darker.yygh.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.enums.OrderStatusEnum;
import com.atguigu.yygh.enums.PaymentStatusEnum;
import com.atguigu.yygh.enums.PaymentTypeEnum;
import com.atguigu.yygh.model.order.OrderInfo;
import com.atguigu.yygh.model.order.PaymentInfo;
import com.atguigu.yygh.vo.order.SignInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.darker.yygh.common.helper.HttpRequestHelper;
import com.darker.yygh.exception.YyghException;
import com.darker.yygh.hosp.client.HospitalFeignClient;
import com.darker.yygh.order.mapper.PaymentMapper;
import com.darker.yygh.order.service.OrderService;
import com.darker.yygh.order.service.PaymentService;
import com.darker.yygh.result.ResultCodeEnum;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class PaymentServiceImpl extends ServiceImpl< PaymentMapper,PaymentInfo> implements PaymentService {

    @Autowired
    OrderService orderService;

    @Autowired
    HospitalFeignClient hospitalFeignClient;

    //支付成功更新订单状态
    @Override
    public void paySuccess(String out_trade_no, Map<String, String> resultmap) {
        //根据订单编号得到支付记录
        LambdaQueryWrapper<PaymentInfo> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(PaymentInfo::getOutTradeNo,out_trade_no)
                .eq(PaymentInfo::getPaymentType, PaymentTypeEnum.WEIXIN.getStatus());
        PaymentInfo paymentInfo = baseMapper.selectOne(queryWrapper);

        //更新支付记录状态
        paymentInfo.setPaymentStatus(PaymentStatusEnum.PAID.getStatus());
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setTradeNo(resultmap.get("transaction_id"));
        paymentInfo.setCallbackContent(resultmap.toString());
        baseMapper.updateById(paymentInfo);

        //根据订单号
        OrderInfo orderInfo = orderService.getById(paymentInfo.getOrderId());
        orderInfo.setOrderStatus(OrderStatusEnum.PAID.getStatus());
        orderService.updateById(orderInfo);

        // 调用医院接口，通知更新支付状态
        SignInfoVo signInfoVo
                = hospitalFeignClient.getSignInfoVo(orderInfo.getHoscode());
        if(null == signInfoVo) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("hoscode",orderInfo.getHoscode());
        reqMap.put("hosRecordId",orderInfo.getHosRecordId());
        reqMap.put("timestamp", HttpRequestHelper.getTimestamp());
        String sign = HttpRequestHelper.getSign(reqMap, signInfoVo.getSignKey());
        reqMap.put("sign", sign);
        JSONObject result = HttpRequestHelper.sendRequest(reqMap, signInfoVo.getApiUrl()+"/order/updatePayStatus");
        if(result.getInteger("code") != 200) {
            throw new YyghException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
        }



    }
    /**
     * 获取支付记录
     * @param orderId
     * @param paymentType
     * @return
     */
    @Override
    public PaymentInfo getPaymentInfo(Long orderId, Integer paymentType) {
        LambdaQueryWrapper<PaymentInfo> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(PaymentInfo::getOrderId,orderId)
                .eq(PaymentInfo::getPaymentType,paymentType);
        PaymentInfo paymentInfo = baseMapper.selectOne(queryWrapper);
        return paymentInfo;

    }

    //向支付记录表添加信息
    @Override
    public void savePaymentInfo(OrderInfo orderInfo, Integer paymentType) {
        LambdaQueryWrapper<PaymentInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PaymentInfo::getOrderId,orderInfo.getId())
                .eq(PaymentInfo::getPaymentType,paymentType);

        //根据订单id和支付类型 查询支付纪律是否存在相同的订单
        Integer count = baseMapper.selectCount(queryWrapper);
        if(count>0){
          return;
        }
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setCreateTime(new Date());
        paymentInfo.setOrderId(orderInfo.getId());
        paymentInfo.setPaymentType(paymentType);
        paymentInfo.setOutTradeNo(orderInfo.getOutTradeNo());
        paymentInfo.setPaymentStatus(PaymentStatusEnum.UNPAID.getStatus());
        String subject = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd")+"|"+orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle();
        paymentInfo.setSubject(subject);
        paymentInfo.setTotalAmount(orderInfo.getAmount());
        baseMapper.insert(paymentInfo);




    }
}
